﻿using System;
using System.Text;
using Tamir.SharpSsh;
using Tamir.SharpSsh.jsch;

namespace Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            ShellHelp shellHelp = new ShellHelp();
            try
            {
                bool isOk = false;
                string msg = "";
                (isOk, msg) = shellHelp.OpenShell(118.24.24.253", "root", "Qq1164185642);
                if (!isOk)
                {
                    Console.WriteLine(msg);
                    Console.ReadLine();
                    return;
                }
                else
                {
                    while (true)
                    {
                        string str = Console.ReadLine();
                        if (string.IsNullOrEmpty(str))
                        {
                            break;
                        }
                        Console.WriteLine();
                        Console.WriteLine(shellHelp.Shell(str));
                        Console.WriteLine();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                shellHelp.Close();
            }


            //Examples.ShellHelp.RunSSHCommands("118.24.24.253", "root", "Qq1164185642.", new string[] { "ls" });
            Console.ReadLine();
        }
    }




    public class ShellHelp
    {
        SshExec exec = null;
        bool IsLoginSuccess = false;

        /// <summary>  
        /// 打开连接  
        /// </summary>  
        /// <param name="host"></param>  
        /// <param name="username"></param>  
        /// <param name="pwd"></param>  
        /// <returns></returns>  
        public (bool, string) OpenShell(string host, string username, string pwd)
        {
            string msg = "";
            try
            {
                exec = new SshExec(host, username, pwd);
                //XXLog.Log(String.Format("[{0}]Connecting...", host));
                exec.Connect();
                IsLoginSuccess = exec.Connected;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return (IsLoginSuccess, msg);
        }
        /// <summary>  
        /// 执行命令  
        /// </summary>  
        /// <param name="cmd"></param>  
        public string Shell(string cmd)
        {
            if (string.IsNullOrEmpty(cmd))
            {
                throw new ArgumentNullException(cmd);
            }
            if (!IsLoginSuccess)
            {
                throw new Exception("未登录授权");
            }
            return exec.RunCommand(cmd);
        }
        

        /// <summary>  
        /// 关闭连接  
        /// </summary>  
        public void Close()
        {
            if (exec != null) exec.Close();
        }
    }
}
